package io.github.echarts.option.serializer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import io.github.echarts.common.exception.RenderException;
import io.github.echarts.option.EChartOption;

/**
 * ECharts配置序列化工具类。
 * 负责将EChartOption对象序列化为JSON字符串，或从JSON字符串反序列化为EChartOption对象。
 */

public class OptionSerializer {
    
    private static final ObjectMapper mapper;
    
    static {
        mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    }
    
    /**
     * 将EChartOption对象序列化为JSON字符串。
     *
     * @param option EChartOption对象
     * @return JSON字符串
     * @throws RenderException 如果序列化过程中发生错误
     */
    public static String toJson(EChartOption option) {
        if (option == null) {
            return "{}";
        }
        
        try {
            return mapper.writeValueAsString(option);
        } catch (JsonProcessingException e) {
            throw new RenderException("Failed to serialize chart option to JSON", e);
        }
    }
    
    /**
     * 将EChartOption对象序列化为格式化的JSON字符串。
     *
     * @param option EChartOption对象
     * @return 格式化的JSON字符串
     * @throws RenderException 如果序列化过程中发生错误
     */
    public static String toPrettyJson(EChartOption option) {
        if (option == null) {
            return "{}";
        }
        
        try {
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(option);
        } catch (JsonProcessingException e) {
            throw new RenderException("Failed to serialize chart option to pretty JSON", e);
        }
    }
    
    /**
     * 从JSON字符串反序列化为EChartOption对象。
     *
     * @param json JSON字符串
     * @return EChartOption对象
     * @throws RenderException 如果反序列化过程中发生错误
     */
    public static EChartOption fromJson(String json) {
        if (json == null || json.trim().isEmpty()) {
            return new EChartOption();
        }
        
        try {
            return mapper.readValue(json, EChartOption.class);
        } catch (Exception e) {
            throw new RenderException("Failed to deserialize JSON to chart option", e);
        }
    }
} 